package com.foreknow.demo10;

import com.foreknow.demo9.Student;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

public class IODemo {
    //对文件写操作
    public void WriteFile(List<Student> list){
        try {
            //创建一个BufferedWriter FileWriter
            FileWriter fw = new FileWriter("student.txt");
            BufferedWriter bw = new BufferedWriter(fw);
            //遍历list集合并获取到学生的信息
            for (Student s:list){
                //写入学生信息
                String str = s.getSid()+" "+s.getName()+" "+s.getSchool()+" "+s.getPhone()+" ";
                bw.write(str);//写入
                bw.newLine();//换行
            }
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //对文件进行读操作
    public List<Student> ReadFile(String fileName){
        FileReader fr = null;
        List<Student> list = new ArrayList<>();
        try {
            fr = new FileReader(fileName);
            //创建一个处理流用于高效的读取
            BufferedReader br = new BufferedReader(fr);
            String str = br.readLine();
            while (str != null){
                Student s = new Student();
                String[] strings = str.split(" ");
                s.setSid(Integer.valueOf(strings[0]));
                s.setName(strings[1]);
                s.setSchool(strings[2]);
                s.setPhone(strings[3]);
                list.add(s);
                str = br.readLine();
            }
            br.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return list;
    }
}
